import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Dashboard from '../components/Dashboard.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Categories from '../components/goods/Categories.vue'
import Parameters from '../components/goods/Parameters.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Edit from '../components/goods/Edit.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'


Vue.use(VueRouter)

const routes = [
  {
    path: '/', redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'dashboard',
        component: Dashboard,
      },
      {
        path: '/users',
        name: 'users',
        component: Users,
      },
      {
        path: '/rights',
        name: 'rights',
        component: Rights,
      },
      {
        path: '/roles',
        name: 'roles',
        component: Roles,
      },
      {
        path: '/categories',
        name: 'categories',
        component: Categories,
      },
      {
        path: '/params',
        name: 'parameters',
        component: Parameters,
      },
      {
        path: '/goods',
        name: 'goods',
        component: List,
      },
      {
        path: '/goods/add',
        component: Add,
      },
      {
        path: '/goods/edit:id',
        name: 'edit',
        component: Edit,
      },
      {
        path: '/orders',
        name: 'orders',
        component: Order,
      },
      {
        path: '/reports',
        name: 'reports',
        component: Report,
      },
    ]
  },
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 放行  next('/login') 强制跳转

  // 如果访问的是登陆页 直接放行
  if (to.path === '/login') return next()
  // 否则判断是否获取了 token 没有强制跳转登陆页 否则放行
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()

})

export default router
